from django.shortcuts import render, redirect
from django.contrib import messages
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings
import os

from ..models import Question, Subject
from ..import_handlers import parse_excel, parse_word, import_from_word

def index(request):
    """考试系统首页视图"""
    context = {
        'title': '考试系统',
        'questions': Question.objects.all()[:10]  # 获取最近的10个题目
    }
    return render(request, 'exam_system/index.html', context)

def import_questions(request):
    step = 1
    context = {'step': step}

    if request.method == 'POST':
        step = int(request.POST.get('step', 1))
        file_full_path = ''

        if step == 1 and request.FILES.get('file'):
            file = request.FILES['file']
            file_extension = os.path.splitext(file.name)[1].lower()

            if file_extension not in ['.xlsx', '.xls', '.docx']:
                messages.error(request, '不支持的文件格式。请上传 Excel 或 Word 文件。')
                return render(request, 'exam_system/import_questions.html', context)

            # 保存上传的文件
            file_path = default_storage.save(f'temp/{file.name}', ContentFile(file.read()))
            file_full_path = os.path.join(settings.MEDIA_ROOT, file_path)

            # 处理预览数据
            if file_extension in ['.xlsx', '.xls']:
                preview_data = parse_excel(file_full_path)[:5]  # 只预览前5条数据
            else:
                # 处理 Word 文件预览
                preview_data = parse_word(file_full_path)[:3]

            context.update({
                'step': 2,
                'file_path': file_path,
                'preview_data': preview_data,
                'subjects': Subject.objects.all()
            })
            return render(request, 'exam_system/import_questions.html', context)

        elif step == 2:
            subject_id = request.POST.get('subject')
            file_path = request.POST.get('file_path')
            if not file_path:
                messages.error(request, '文件路径未找到，请重新上传文件。')
                return render(request, 'exam_system/import_questions.html', {'step': 1})

            file_full_path = os.path.join(settings.MEDIA_ROOT, file_path)
            if not os.path.exists(file_full_path):
                messages.error(request, '文件不存在，请重新上传文件。')
                return render(request, 'exam_system/import_questions.html', {'step': 1})

            try:
                subject = Subject.objects.get(id=subject_id)
                file_extension = os.path.splitext(file_full_path)[1].lower()

                # 从EXCEL文件中导入
                if file_extension in ['.xlsx', '.xls']:
                    questions = parse_excel(file_full_path)
                    # 导入试题
                    for question_data in questions:
                        Question.objects.create(
                            subject=subject,
                            content=question_data['content'],
                            question_type=question_data['question_type'],
                            options=question_data['options'],
                            answer=question_data['answer'],
                            image=question_data['image'],  # 使用正确的字段名
                            image_name=question_data.get('image_name'),  # 添加image_name字段
                            difficulty=question_data['difficulty']
                        )
                    imported_count = len(questions)

                # 从WORD文件中导入
                else:
                    imported_count = import_from_word(file_full_path, subject_id)

                context.update({
                    'step': 3,
                    'success': True,
                    'imported_count': imported_count,
                    'error_count': 0
                })
            except Exception as e:
                context.update({
                    'step': 3,
                    'success': False,
                    'errors': [str(e)]
                })
            finally:
                # 删除临时文件
                # 在Windows上，文件可能被pandas或openpyxl库占用，需要确保先关闭文件
                try:
                    # 强制关闭所有可能的文件句柄
                    import gc
                    gc.collect()  # 强制垃圾回收，释放文件句柄

                    # 尝试删除文件，如果失败则忽略错误
                    if os.path.exists(file_full_path):
                        try:
                            os.remove(file_full_path)
                        except PermissionError:
                            # 如果文件被占用，记录日志但不中断流程
                            print(f"警告：无法删除临时文件 {file_full_path}，可能被其他程序占用")
                        except Exception as e:
                            print(f"删除临时文件时出错: {str(e)}")
                except Exception as e:
                    print(f"清理过程中出错: {str(e)}")

            return render(request, 'exam_system/import_questions.html', context)

    return render(request, 'exam_system/import_questions.html', context)